define (require, exports, module) ->
  # 登录组件css
  require 'mods/login/login_css.css'
  # 服务接口
  login_api =  require 'mods/login/login_api'
  # 图形验证码
  captcha_api = require 'mods/api/captcha_api'
  # 引入风险信息字典
  riskInfo = require 'js/risk_dict.json'

  bus = require 'mods/bus'

  # 定义组件
  module.exports = Vue.extend
    # 变量声明
    data: () ->
      # 是否加载完成
      loadedSucc: false
      # 加载失败提示语
      loadedFail: ''
      # 登录信息
      user: {}
      # 图形验证码
      captchaSrc: ''
      # 图形验证码输入值
      captchaVal: ''
      # 错误类型  0无错，1用户名，2密码，3验证码
      errorType: 0
      # 工具条提示
      topTipsOption: {}
      # header是否已成功获取风险等级信息
      infoStatus: false
      # 用户信息
      userInfo: {}

    # 组件模板
    template: require 'mods/login/login_tpl.js'

    # 组件方法
    methods:

      # 弹出错误提示
      alertTipError: (content) ->
        self = @
        self.alertTip 'error', content
        return false

      # 弹出成功提示
      alertTipSuccess: (content) ->
        self = @
        self.alertTip 'success', content
        return false

      # 弹出提示
      alertTip: (tip_type, content) ->
        self = @
        # 工具条提示
        topTipsObj =
          state: true
          auto_close: true
          tip_type: tip_type
          content: content
        self.topTipsOption = Vue.util.extend {}, topTipsObj

      # 判断登录错误类型
      checkErrorType: (errInfo) ->
        self = @
        if -1 isnt errInfo?.indexOf '验证码'
          self.errorType = 3
        else if '登录用户不存在！' is errInfo or '登录用户信息必填！' is errInfo or '登录手机号码必填！' is errInfo or '登录-用户名或密码错误！' is errInfo
          self.errorType = 1
        else if -1 isnt errInfo?.indexOf '密码'
          self.errorType = 2

      # 执行登录
      doLogin: () ->
        self = @
        # 登录参数
        params =
          user: self.user
          captcha: self.captchaVal

        # 提交登录
        login_api.doLogin params

          .then (res) ->

            if 200 isnt res?.status

              self.refreshCaptcha()
              self.alertTipError res?.error or res?.data?.error or "登录失败"
              self.checkErrorType res?.error or res?.data?.error

            else

              # 登录成功获取用户信息
              self.getUserSession()

                .then (res) ->

                  # 判断交易接口是否出错
                  if (not self.userInfo.hasOwnProperty 'client_id') or (not self.userInfo.hasOwnProperty 'risk_level')
                    self.alertTipError '接口出错，暂时无法登录，请联系管理员'
                    return false

                  # 将信息保存在sessionStorage中
                  self.saveUserSession()

                  # 提交登录状态
                  bus.$emit 'login_stu', 'success'

                  goUrl = self.$route.query.redirect

                  if not goUrl
                    self.$router.push {path: '/'}

                  else
                    self.$router.push {path: goUrl}
                
                .catch (err) ->
                  console.error 'err:',err

          .catch (err) ->
            self.refreshCaptcha()
            self.alertTipError err?.data?.error or "未知的异常，请重新登录"
            self.checkErrorType err?.data?.error

      doReg: () ->
        self = @
        self.$router.push {path: '/reg'}

      # 刷新验证码
      refreshCaptcha: () ->
        self = @
        self.captchaSrc = captcha_api.getCaptcha()

      # 获取用户登录信息
      getUserSession: () ->
        self = @

        return login_api.getUserSession()

          .then (res) ->

            if 200 isnt res?.status
              console.error 'sessionErrCode:',res?.status

            else

              self.userInfo = res?.body

              # 获取用户风险等级信息
              self.getUserRiskInfo()

                .then (res) ->

                  # 查询客户信息
                  self.queryClientInfo()

                .catch (err) ->
                  console.error 'err:',err

          .catch (err) ->
            console.error '获取用户信息出错：', err

      # 获取用户风险等级信息
      getUserRiskInfo: () ->
        self = @
        params =
          "id_no": self.userInfo.id_no
          "id_kind": self.userInfo.id_kind
          "dsorgan_flag": '0'

        return login_api.getUserRiskInfo params
          
          .then (res) ->
            
            if 200 isnt res?.status
              console.log 'riskErrCode:', res?.status
            
            else
              
              risk_level = 0
              
              if 0 is res?.data?.table_data?.length
                risk_level = 0
              
              else
                risk_level = res?.data?.table_data[0]?.corp_risk_level
                tzpz = res?.data?.table_data[0]?.client_invest_type
                tzqx = res?.data?.table_data[0]?.client_term_type

              # 用户适当性三要素添加到sessionStorage
              self.userInfo.risk_level_name = riskInfo[0][risk_level]?.risk_level_name
              self.userInfo.risk_level = risk_level
              self.userInfo.tzpz_name = riskInfo[2][tzpz-1]?.tzpz_name
              self.userInfo.tzpz = tzpz
              self.userInfo.tzqx_name = riskInfo[1][tzqx-1]?.tzqx_name
              self.userInfo.tzqx = tzqx

          .catch (err) ->
            console.error '获取用户风险等级信息出错：', err

      # 查询客户信息
      queryClientInfo: () ->
        self = @
        params =
          client_id: ''
          id_kind: self.userInfo?.id_kind
          id_no: self.userInfo?.id_no
          prodta_no: '87'
          agency_no: 'GF9'
          dsorgan_flag: '0'

        return login_api.queryClientInfo params
          .then (res) ->
            tmpArr = res?.data?.table_data
            # 请求成功
            if 0 is res?.data?.error_no
              # 返回结果为空，则未开开客户
              if 0 is tmpArr?.length
                self.userInfo.client_id = '未绑定'
              # 返回结果不为空，则已开客户号
              else
                self.userInfo.client_id = tmpArr[0]?.client_id

          .catch (err) ->
            console.error 'err:',err

      # 登录成功后保存session
      saveUserSession: () ->

        self = @

        # 设置登录状态
        self.userInfo.logined = true

        # 先把JSON转化成字符串
        tmpObj = JSON.stringify self.userInfo

        # 将用户信息存储在sessionStorage中
        sessionStorage.setItem 'userInfo', tmpObj

    # 实例创建时触发
    created: () ->
      self = @
      # 刷新图形验证码
      self.refreshCaptcha()

    components:
      'c-top-tips': require 'mods/top_tips/top_tips_mod'

    # 计算属性
    computed:
      # 加载中的样式
      loaddingClass: () ->
        self = @
        if self.loadedSucc
          return 'c-hidden'
        if self.loadedFail
          return 'c-hidden'
        return ''

      # 加载成功的样式
      loadedSuccClass: () ->
        self = @
        return if self.loadedSucc then '' else 'c-vhidden'

      # 加载失败的样式
      loadedFailClass: () ->
        self = @
        return if self.loadedFail then '' else 'c-hidden'

    # 组件初始化执行
    mounted: () ->
      self = @
      setTimeout () ->
        Vue.nextTick () ->
          # 加载成功标识
          self.loadedSucc = true
      , 5